package com.wing.sms.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.wing.sms.dao.SmsDao;
import com.wing.sms.model.Sms;
import com.wing.sms.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Date;
import java.util.Map;


/**
 * * 程序名 : AliyunSmsConfig
 * 模块 : 短信中心
 * 描述 : 调用阿里短信接口
 */
@Slf4j
@Service
public class SmsServiceImpl implements SmsService {

	@Autowired
	private Client client;
	@Value("${aliyun.sms.sign.name:xxxxxx}")
	private String signName;
	@Value("${aliyun.sms.template.code:xxxxx}")
	private String templateCode;
	@Value("${aliyun.sms.yunDuanSign.name:xxxxxx}")
	private String yunDuanSignName;


	@Autowired
	private SmsDao smsDao;

	@Override
	@Transactional
	public SendSmsResponse sendSmsMsg(Sms sms) throws Exception{
		 SendSmsRequest sendSmsRequest = new SendSmsRequest()
				 .setSignName(sms.getSignName())
				 .setTemplateCode(sms.getTemplateCode())
				 .setPhoneNumbers(sms.getPhone())
				 .setTemplateParam(sms.getParams());
		com.aliyun.teautil.models.RuntimeOptions runtime = new com.aliyun.teautil.models.RuntimeOptions();

		// 复制代码运行请自行打印 API 的返回值
		SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtime);
		sms.setSignName(signName);
		sms.setTemplateCode(templateCode);
		update(sms);
		log.info(sendSmsResponse.getBody().getCode()+","+sendSmsResponse.getBody().getMessage());
		return null;
	}

	
	@Override
	public void save(Sms sms, Map<String, String> params) {
		if (!CollectionUtils.isEmpty(params)) {
			sms.setParams(JSONObject.toJSONString(params));
		}

		sms.setCreateTime(new Date());
		sms.setUpdateTime(sms.getCreateTime());
		sms.setDay(sms.getCreateTime());

		smsDao.save(sms);
	}

	@Transactional
	@Override
	public void update(Sms sms) {
		sms.setUpdateTime(new Date());
		smsDao.update(sms);
	}

	@Override
	public Sms findById(Long id) {
		return smsDao.findById(id);
	}

	 public static void main(String args[]) {
		 //         SendSmsRequest sendSmsRequest = new SendSmsRequest()
		 //                    .setSignName("阿里云短信测试")
		 //                    .setTemplateCode("SMS_154950909")
		 //                    .setPhoneNumbers("17375884287")
		 //                    .setTemplateParam(random);
		 //
		 //
		 //            //存入缓存
		 //            redisHelper.valuePut("phoneCode", phone);
		 //            // 复制代码运行请自行打印 API 的返回值
		 //            client.sendSms(sendSmsRequest);
	  }

}
